package com.hwh.bootdemoweb.Netty第六章;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

/**
 * @author wenhao hu
 * @title: EventLoopServer
 * @projectName bootdemoweb
 * @description: TODO
 * @date 2021/12/1711:57
 */
@Slf4j
public class EventLoopServer {
    public static void main(String[] args) {
        //细分二：创建一个独立的EventLoopGroup 用来处理非NIO任务
        EventLoopGroup group = new DefaultEventLoopGroup();
        new ServerBootstrap()
                //细分一：可以再细分，用两组eventLoop来分别处理不同的事件 ServerSocketChannel只会根据一个Group进行绑定
                .group(new NioEventLoopGroup(),new NioEventLoopGroup(2))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        //细分二：给Handler添加到DGroup里，这样他就不会用Nio的EventGroup，而是DGroup
                        ch.pipeline().addLast("Handler1",new ChannelInboundHandlerAdapter(){
                            @Override                                           //ByteBuf
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = (ByteBuf) msg;
                                //最好强制指定字符集，以防出现客户端服务端字符集不一致导致的乱码
                                log.debug(buf.toString(Charset.defaultCharset()));
                                //将消息传递给下一个Handler
                                ctx.fireChannelRead(msg);
                            }
                        }).addLast(group,"Handler2",new ChannelInboundHandlerAdapter(){
                            @Override                                           //ByteBuf
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = (ByteBuf) msg;
                                //最好强制指定字符集，以防出现客户端服务端字符集不一致导致的乱码
                                log.debug(buf.toString(Charset.defaultCharset()));
                            }
                        });
                    }
                }).bind(8080);
    }
}
